<template>
  <div>
    <x-breadcrumb :content-list="contentList"></x-breadcrumb> <!-- 面包屑导航 -->

    <el-card class="box-card mt-3">
      <alert-and-steps redactOrAdd :active="active"></alert-and-steps>
      <el-form label-position="top" :model="redactFormVal" ref="rulesForm" :rules="rules">
        <el-tabs tab-position="left" v-model="tabsVal" @tab-click="tabPaneNameClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="redactFormVal.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="redactFormVal.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="redactFormVal.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="redactFormVal.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <x-cascader @cascader-data="dataValEve" redactOrAdd></x-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <product-params></product-params>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <product-attribute></product-attribute>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <x-upload></x-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <div class="quill-editor" ref="quillEditorDom"></div>
            <el-button type="primary" class="editGoods mt-3" @click="updateBtn">更新商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, computed, watch, ref, reactive, Ref, ComputedRef } from 'vue'
import XBreadcrumb, { contentType } from '@/components/public-components/XBreadcrumb.vue'
import { useStore } from '@/store'
import E from "wangeditor"
import { ProductListRedactProps } from '@/store/storeType'
import alertAndSteps from '@/components/goods/privateComponents/alertAndSteps.vue'
import XCascader from '@/components/goods/privateComponents/XCascader.vue'
import XUpload from '@/components/goods/privateComponents/XUpload.vue'
import ProductParams from '@/components/goods/privateComponents/ProductParams.vue'
import ProductAttribute from '@/components/goods/privateComponents/ProductAttribute.vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

// 富文本逻辑
const EditorFn = (dom: Ref<HTMLElement | undefined>) => {
  // 富文本编辑器节点获取
  let editor: any = null
  // 富文本编辑器注册到节点
  watch<HTMLElement>(() => dom.value as HTMLElement, (val: HTMLElement) => {
    editor = new E(val)
    editor.config.height = 'auto'
    editor.create()
  })
  // 更新实例
  const editorData = computed(() => editor)
  return { editorData }
}


// 更新内容
const UpdateFn = (editorData: ComputedRef, rulesForm: Ref<HTMLFormElement | undefined>) => {
  const store = useStore()
  // 更新内容按钮
  const updateBtn = () => {
    // 更新富文本的内容
    if (store.state.productList.redactModule.redactData.goods_introduce) {
      store.state.productList.redactModule.redactData.goods_introduce = editorData.value?.txt.html()
    }
    (rulesForm.value as HTMLFormElement).validate((valid: boolean) => {
      if (!valid) { // 是否通过表单验证
          ElMessage({
          type: 'error',
          message: '表单不合法',
          center: true,
          showClose: true
        })
        return
      }
      // 获取 各个数据
      const { goods_name, goods_price, goods_weight, goods_cat, goods_number, goods_introduce, pics, attrs } = store.state.productList.redactModule.redactData
      // attrs 请求数据的拼接
      const attrsNewArr = attrs?.map(item => {
        return { attr_id: item.attr_id, attr_value: item.attr_value }
      })
      // pics 请求数据的拼接
      const picsUrlArr = pics?.filter(item => {
        if (item.pic) {
          return { pic: item.pic }
        }
      })
      // 发送更新数据
      store.dispatch('postGoodsData', { goods_name, goods_price, goods_weight, goods_cat, goods_number, goods_introduce, pics: picsUrlArr, attrs: attrsNewArr })
      ElMessage({
        type: 'success',
        message: '更新商品成功',
        center: true,
        showClose: true
      })
    })
  }
  return { updateBtn }
}

// 左边tabs 逻辑
const tabsFn = (tabsVal: Ref<string>, selectId: Ref<any>, editorData: ComputedRef) => {
  const store = useStore()
  // tabs 发送请求获取数据
  const tabPaneNameClick = () => {
    if (tabsVal.value === '1') {
      store.dispatch('productList/redactModule/getAttributes', { cid: selectId.value[2], sel: 'many' })
    } else if (tabsVal.value === '2') {
      store.dispatch('productList/redactModule/getAttributes', { cid: selectId.value[2], sel: 'only' })
    } else if (tabsVal.value === '4') {
      editorData.value?.txt.append(store.state.productList.redactModule.redactData.goods_introduce)
    }
  }

  return { tabPaneNameClick }
}

// form表单双向绑定 和 表单验证规则
const formDataFn = () => {
  const store = useStore()
  // form表单双向绑定
  const redactFormVal = computed<ProductListRedactProps>({
    get: () => store.state.productList.redactModule.redactData,
    set: val => (store.state.productList.redactModule.redactData = {...store.state.productList.redactModule.redactData, ...val})
  })
  // 表单验证规则绑定
  const rules = reactive({
    goods_name: [
      {required: true, message: '请输入商品名称', trigger: 'blur'}
    ],
    goods_price: [
      {required: true, message: '请输入商品价格', trigger: 'blur'}
    ],
    goods_weight: [
      {required: true, message: '请输入商品重量', trigger: 'blur'}
    ],
    goods_number: [
      {required: true, message: '请输入商品数量', trigger: 'blur'}
    ],
    goods_cat: [
      {required: true, message: '请输入商品分类', trigger: 'blur'}
    ],
  })

  return { redactFormVal, rules }
}

const contentList: contentType[] = ['首页', '商品管理', '编辑商品']

export default defineComponent({
  name: 'ProductListRedact',
  components: {
    XBreadcrumb,
    alertAndSteps,
    XUpload,
    ProductParams,
    ProductAttribute,
    XCascader
  },
  setup () {
    // 表单dom
    const rulesForm = ref<HTMLFormElement>()
    // 富文本编辑器节点获取
    const quillEditorDom = ref<HTMLElement>()
    
    // 富文本逻辑
    const { editorData } = EditorFn(quillEditorDom)

    // 步骤条绑定数据
    const store = useStore()
    const route = useRoute()
    const { id } = route.query
    const tabsVal = ref('0')
    const selectDataValue = ref('')
    const dataValEve = (val: any) => {
      selectDataValue.value = val
    }
    const active = computed(() => +tabsVal.value) // 步骤条绑定
    // 请求初始化数据
    onMounted(() => {
      store.dispatch('productList/redactModule/getProductData', id)
      store.dispatch('getCategoriesList')
    })

    const { redactFormVal, rules } = formDataFn() // 表单验证和表单双向绑定更新数据
    
    const { tabPaneNameClick } = tabsFn(tabsVal, selectDataValue, editorData) // tabs 组件逻辑

    const { updateBtn } = UpdateFn(editorData, rulesForm) // 更新数据按钮


    
    return { redactFormVal, tabsVal,
      tabPaneNameClick, quillEditorDom, updateBtn, rules, rulesForm, active, contentList, dataValEve }
  }
})
</script>
